package top.frsf.mqtt.handler.strategy;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.mqtt.MqttMessage;
import io.netty.handler.codec.mqtt.MqttMessageType;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import top.frsf.mqtt.handler.strategy.abs.MqttMessageHandlerStrategy;
import top.frsf.mqtt.session.SessionManager;

/**
 * MQTT协议事件 - 断连事件处理器
 *
 * @author He Kuntao
 * @since 2025/5/29 14:15
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class DisconnectMessageHandler implements MqttMessageHandlerStrategy {

    private final SessionManager sessionManager;

    @Override
    public void handle(ChannelHandlerContext ctx, MqttMessage message) {
        String clientId = sessionManager.getClientIdByChannel(ctx.channel());
        if (clientId != null) {
            sessionManager.removeClient(clientId);
            log.info("Client disconnected: {}", clientId);
        }
        ctx.close();
    }

    @Override
    public MqttMessageType supportedType() {
        return MqttMessageType.DISCONNECT;
    }
}
